﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Configuration;
using System.Diagnostics;

namespace DirCopy
{
    public partial class Form1 : Form
    {
        System.Configuration.Configuration m_config;//程序配置文件

        public Form1()
        {
            InitializeComponent();
            AutoStart();
        }

        public void AutoStart()
        {
            
            m_config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            System.Configuration.AppSettingsSection appSettings = m_config.AppSettings;

            if (appSettings.Settings["AutoStart"] != null)
            {
                txtSourcePath.Text = appSettings.Settings["SourcePath"].Value;
                txtTargetPath.Text = appSettings.Settings["TargetPath"].Value;
                if (appSettings.Settings["AutoStart"].Value == "yes")
                {
                    cbAutoStart.Checked = true;
                    PauseAuto();
                    //CopyDirectory(txtSourcePath.Text, txtTargetPath.Text);
                }
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            string sourceDirectory = @"Q:\HTMLs";
            string targetDirectory = @"Q:\test";
            //CopyDirectory(sourceDirectory, targetDirectory);
            m_config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            System.Configuration.AppSettingsSection appSettings = m_config.AppSettings;

            if (appSettings.Settings["AutoStart"] != null)
            {
                if (cbAutoStart.Checked)
                    appSettings.Settings["AutoStart"].Value = "yes";
                else
                    appSettings.Settings["AutoStart"].Value = "no";
                appSettings.Settings["SourcePath"].Value = txtSourcePath.Text;
                appSettings.Settings["TargetPath"].Value = txtTargetPath.Text;
            }
            else
            {
                appSettings.Settings.Add("AutoStart", "");
                appSettings.Settings.Add("SourcePath", "");
                appSettings.Settings.Add("TargetPath", "");
                if (cbAutoStart.Checked)
                    appSettings.Settings["AutoStart"].Value = "yes";
                else
                    appSettings.Settings["AutoStart"].Value = "no";
                appSettings.Settings["SourcePath"].Value = txtSourcePath.Text;
                appSettings.Settings["TargetPath"].Value = txtTargetPath.Text;
            }
            m_config.Save(ConfigurationSaveMode.Full);
            ConfigurationManager.RefreshSection("appSettings");
        }

        private bool LoadSharedDriver(out string err)
        {
            string usr = @"tonyye";
            string pwd = @"yetony";
            string remoteurl = @"\\192.168.2.88\export";
            string localdisk = txtSourcePath.Text.Substring(0, 2);

            Process p = new Process();
            string strspace = " ";
            p.StartInfo.FileName = "net.exe";
            //p.StartInfo.Arguments = @"use y: \\192.168.2.88\export yetony /user:tonyye";
            p.StartInfo.Arguments = @"use "+localdisk + strspace + remoteurl + strspace + pwd + strspace + @"/user:"+usr;
            p.StartInfo.UseShellExecute = false;
            //p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            //p.StartInfo.CreateNoWindow = true;
            p.Start();

            //p.StandardInput.WriteLine("E:\bat\netuse.bat" + "&exit");
            //p.StandardInput.AutoFlush = true;

            string output = p.StandardOutput.ReadToEnd();
            err = p.StandardError.ReadToEnd();

            p.WaitForExit();
            p.Close();

            if (err == "")
            {
                return true;
            }
            err = output + err;


            /*
            Process.Start("net", @"use y: \\192.168.2.88\export yetony /user:tonyye");
             */
            return false;
        }


        public void CopyDirectory(string SourceDirectory, string TargetDirectory)
        {
            DirectoryInfo   source = new DirectoryInfo(SourceDirectory);
            DirectoryInfo   target = new DirectoryInfo(TargetDirectory);
         
            //Check If we have valid source
            if (!source.Exists)
            {
                string err;
                if (LoadSharedDriver(out err) == false)
                {
                    MessageBox.Show(source.FullName + "is not exists, please check" + err, "DirCopy");
                    return;
                }
            }
            if (target.Name != source.Name)
                target = new DirectoryInfo(target.FullName + "\\" + source.Name);

            if (!target.Exists)
                target.Create();
            
         
            //Copy Files
            FileInfo[] sourceFiles = source.GetFiles();   
            for(int i = 0; i < sourceFiles.Length; ++i)
                File.Copy(sourceFiles[i].FullName, target.FullName + "\\" + sourceFiles[i].Name,true);
         
            //Copy directories
            DirectoryInfo[] sourceDirectories = source.GetDirectories();
            for (int j = 0; j < sourceDirectories.Length; ++j)
                CopyDirectory(sourceDirectories[j].FullName, target.FullName + "\\" + sourceDirectories);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBr = new FolderBrowserDialog();

            folderBr.SelectedPath = txtSourcePath.Text;

            if (folderBr.ShowDialog() == DialogResult.OK)
            {
                txtSourcePath.Text = folderBr.SelectedPath;
            }
        }

        private void btnTargetFolder_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBr = new FolderBrowserDialog();

            folderBr.SelectedPath = txtTargetPath.Text;

            if (folderBr.ShowDialog() == DialogResult.OK)
            {
                txtTargetPath.Text = folderBr.SelectedPath;
            }
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            CopyDirectory(txtSourcePath.Text, txtTargetPath.Text);
            if ( cbAutoStart.Checked)
                ExitAuto();
        }

        private void PauseAuto()
        {
            Timer timer = new Timer();
            timer.Interval = 30000; // 30 seconds
            timer.Tick += new EventHandler(button2_Click_1);
            timer.Start();
            lblStatus.Text = "Auto copy will start in " +timer.Interval/1000 + " seconds";
            
        }

         private void ExitAuto()
        {
            Timer timer = new Timer();
            timer.Interval = 30000; // 30 seconds
            timer.Tick += new EventHandler(exit);
            timer.Start();
            lblStatus.Text = "Application will be closed in " +timer.Interval/1000 + " seconds";
        }

         private void exit(object sender, EventArgs e)
         {
             Application.Exit();
         }

    }
}
